下面示例显示 C 和 Python 中 if-else 语句的语法和语义非常相似。主要的语法差异是 Python 使用缩进来指示“body”语句,而 C 使用大括号(但仍然应该在 C 代码中使用良好的缩进)。

# Python if-else example

def main():

    num1 = input("Enter the 1st number:")
    num1 = int(num1)
    num2 = input("Enter the 2nd number:")
    num2 = int(num2)

    if num1 > num2:
        print("%d is biggest" % num1)
        num2 = num1
    else:
        print("%d is biggest" % num2)
        num1 = num2


# call the main function:
main()
/* C if-else example */
#include <stdio.h>

int main(void) {
    int num1, num2;

    printf("Enter the 1st number: ");
    scanf("%d", &num1);
    printf("Enter the 2nd number: ");
    scanf("%d", &num2);

    if (num1 > num2) {
        printf("%d is biggest\n", num1);
        num2 = num1;
    } else {
        printf("%d is biggest\n", num2);
        num1 = num2;
    }

    return 0;
}

Python 和 C 的 if-else 语句语法几乎相同,仅存在细微差别。在这两种情况下,else 部分都是可选的。 Python 和 C 还通过链接 if 和 else if 语句来支持多路分支。下面描述了完整的 if-else C 语法:

	// a one-way branch:
    if ( <boolean expression> ) {
        <true body>
    }

    // a two-way branch:
    if ( <boolean expression> ) {
        <true body>
    }
    else {
        <false body>
    }

    // a multibranch (chaining if-else if-...-else)
    // (has one or more 'else if' following the first if):
    if ( <boolean expression 1> ) {
        <true body>
    }
    else if ( <boolean expression  2> ) {
        // first expression is false, second is true
        <true 2 body>
    }
    else if ( <boolean expression  3> ) {
        // first and second expressions are false, third is true
        <true 3 body>
    }
    // ... more else if's ...
    else if ( <boolean expression  N> ) {
        // first N-1 expressions are false, Nth is true
        <true N body>
    }
    else { // the final else part is optional
        // if all previous expressions are false
        <false body>
    }

1.3.1 C 中的布尔值

C 不提供具有 true 或 false 值的布尔类型。相反,当在条件语句中使用整数值时,其计算结果为 true 或 false。当用于条件表达式时,任何整数表达式:

  • 零 (0) 计算结果为 false
  • 非零(任何正值或负值)计算结果为 true

C 有一组用于布尔表达式的关系运算符和逻辑运算符。

关系运算符采用相同类型的操作数并计算为零(false)或非零(true)来表示bool值。关系运算符集是:

  • 相等(==)和不相等(不相等,!=)
  • 比较运算符:小于 (<)、小于或等于 (<=)、大于 (>) 和大于或等于 (>=)

以下是一些关系运算符示例的 C 代码片段

// assume x and y are ints, and have been assigned
// values before this point in the code

if (y < 0) {
    printf("y is negative\n");
} else if (y != 0) {
    printf("y is positive\n");
} else {
    printf("y is zero\n");
}

// set x and y to the larger of the two values
if (x >= y) {
    y = x;
} else {
    x = y;
}

C 的逻辑运算符采用整数“布尔”操作数并计算为零(假)或非零(真)表示bool值。逻辑运算符集有:

  • 逻辑否定 (!)
  • 逻辑与 (&&):在第一个错误表达式处停止计算(短路)
  • 逻辑或 (||):在第一个真表达式处停止计算(短路)

C 的短路逻辑运算符计算在结果已知后立即停止计算逻辑表达式。例如,如果逻辑 and (&&) 表达式的第一个操作数的计算结果为 false,则 && 表达式的结果必须为 false。因此,不需要评估第二个操作数的值,也不会评估它。

以下是使用逻辑运算符的 C 条件语句示例(最好在复杂的布尔表达式周围使用括号,以使其更易于阅读):

if ( (x > 10) && (y >= x) ) {
    printf("y and x are both larger than 10\n");
    x = 13;
} else if ( ((-x) == 10) || (y > x) ) {
    printf("y might be bigger than x\n");
    x = y * x;
} else {
    printf("I have no idea what the relationship between x and y is\n");
}

1.3.2 C 中的循环

与 Python 一样,C 支持 for 和 while 循环。此外,C 还提供 do-while 循环

while 循环

C 和 Python 中的 while 循环语法几乎相同,并且行为也相同。以下是 C 和 Python 中 while 循环的示例程序。

# Python while loop example

def main():
    num = input("Enter a value: ")
    num = int(num)
    # make sure num is not negative
    if num < 0:
        num = -num

    val = 1
    while val < num:
        print("%d" % (val))
        val = val * 2

# call the main function:
main()
/* C while loop example */
#include <stdio.h>

int main(void) {
    int num, val;

    printf("Enter a value: ");
    scanf("%d", &num);
    // make sure num is not negative
    if (num < 0) {
        num = -num;
    }
    val = 1;
    while (val < num) {
        printf("%d\n", val);
        val = val * 2;
    }

    return 0;
}

C 中的 while 循环语法与 Python 中非常相似,并且两者的计算方式相同:

while ( <boolean expression> ) {
    <true body>
}

while 循环首先检查布尔表达式,如果为真则执行主体。在前面的示例程序中,val 变量的值将在 while 循环中重复打印,直到其值大于 num 变量的值。如果用户输入 10,C 和 Python 程序将打印:

1
2
4
8

C 也提供do-while 循环,与其 while 循环类似,但它首先执行循环体,然后检查条件,只要条件为真,就重复执行循环体。也就是说,do-while 循环将始终执行循环体至少一次:

do {
    <body>
} while ( <boolean expression> );

有关其他 while 循环示例,请尝试以下两个程序:

/*
 * Copyright (c) 2020, Dive into Systems, LLC (https://diveintosystems.org/)
 * An example of a basic while loop.
 */
#include <stdio.h>

int main(void) {
    int i;

    i = 0;
    while (i < 10) {
        printf("i is %d\n", i++);  // i++: increment i's value after using it
    }
    return 0;
}
/* Copyright (c) 2020, Dive into Systems, LLC (https://diveintosystems.org/)
 *
 * An example of a typical while loop used to force the user to
 * enter valid input.
 */
#include <stdio.h>

int main(void) {
    int data;

    while (1) {  // an infinite loop (1 is always true)
        printf("Enter a value beween 0 and 100: ");
        scanf("%d", &data);
        if ((data >= 0) && (data <= 100)){
            break;  // break out of a loop
        }
        printf("Hey, %d isn't between 0 and 100...try again\n", data);
    }

    printf("The value read in is %d\n", data);
    return 0;
}

for 循环

C 中的 for 循环与 Python 中的不同。在 Python 中,for 循环是序列上的迭代,而在 C 中,for 循环是更通用的循环结构。以下显示了使用 for 循环打印 0 到用户提供的输入数字之间的所有值的示例程序:

# Python for loop example

def main():
    num = input("Enter a value: ")
    num = int(num)
    # make sure num is not negative
    if num < 0:
        num = -num


    for i in range(num):
        print("%d" % i)

# call the main function:
main()
/* C for loop example */
#include <stdio.h>

int main(void) {
    int num, i;

    printf("Enter a value: ");
    scanf("%d", &num);
    // make sure num is not negative
    if (num < 0) {
        num = -num;
    }

    for (i = 0; i < num; i++) {
        printf("%d\n", i);
    }

    return 0;
}

在此示例中,您可以看到 C for 循环语法与 Python for 循环语法有很大不同。也有不同的校验。 C for 循环语法是:

for ( <initialization>; <boolean expression>; <step> ) {
    <body>
}

for循环评估规则为:

  1. 第一次进入循环时评估一次初始化。
  2. 评估布尔表达式。如果为 0(假),则退出 for 循环(即,程序完成重复循环体语句)。
  3. 评估循环体内的语句。
  4. 评估步骤表达式。
  5. 从步骤 (2) 开始重复。

下面是一个简单的 for 循环示例,用于打印值 0、1 和 2:

int i;

for (i = 0; i < 3; i++) {
    printf("%d\n", i);
}

在前面的循环上执行 for 循环评估规则会产生以下操作序列:

(1) eval init: i is set to 0  (i=0)
(2) eval bool expr: i < 3 is true
(3) execute loop body: print the value of i (0)
(4) eval step: i is set to 1  (i++)
(2) eval bool expr: i < 3 is true
(3) execute loop body: print the value of i (1)
(4) eval step: i is set to 2  (i++)
(2) eval bool expr: i < 3 is true
(3) execute loop body: print the value of i (2)
(4) eval step: i is set to 3  (i++)
(2) eval bool expr: i < 3 is false, drop out of the for loop

以下程序显示了一个更复杂的 for 循环示例。请注意,正因为 C 支持带有用于初始化和步骤部分的语句列表的 for 循环,所以最好保持简单(此示例说明了更复杂的 for 循环语法,但如果它通过将 j += 10 步骤语句移动到循环体的末尾并只有一个步骤语句 i += 1) 进行了简化。

/* An example of a more complex for loop which uses multiple variables.
 * (it is unusual to have for loops with multiple statements in the
 * init and step parts, but C supports it and there are times when it
 * is useful...don't go nuts with this just because you can)
 */
#include <stdio.h>

int main(void) {
    int i, j;

    for (i=0, j=0; i < 10; i+=1, j+=10) {
        printf("i+j = %d\n", i+j);
    }

    return 0;
}

// the rules for evaluating a for loop are the same no matter how
// simple or complex each part is:
// (1) evaluate the initialization statements once on the first
//     evaluation of the for loop:  i=0 and j=0
// (2) evaluate the boolean condition: i < 10
//     if false (when i is 10), drop out of the for loop
// (3) execute the statements inside the for loop body: printf
// (4) evaluate the step statements:  i += 1, j += 10
// (5) repeat, starting at step (2)

在 C 语言中,for 循环和 while 循环在功能上是等效的,这意味着任何 while 循环都可以表示为 for 循环,反之亦然。在 Python 中情况并非如此,其中 for 循环是对一系列值的迭代。因此,它们无法表达等效的更通用的 Python while 循环所表达的一些循环行为。

参考 C 中的以下 while 循环:

int guess = 0;

while (guess != num) {
    printf("%d is not the right number\n", guess);
    printf("Enter another guess: ");
    scanf("%d", &guess);
}```
该循环可以转换为 C 中的等效 for 循环:
```c
int guess;

for (guess = 0; guess != num; ) {
    printf("%d is not the right number\n", guess);
    printf("Enter another guess: ");
    scanf("%d", &guess);
}

然而,在 Python 中,这种类型的循环行为只能通过使用 while 循环来表达。

由于 for 和 while 循环在 C 中具有同等的表达能力,因此该语言中只需要一种循环结构。然而,for 循环是适用于确定循环(例如迭代一系列值)的一种更自然的语言构造,而 while 循环是适用于不定循环(例如重复直到用户输入偶数)的更自然的语言构造。因此,C 为程序员提供了这两种功能。